#include "Region.h"

using namespace std;

int Region::nbRegion = 0;

Region::Region(const int  _x1, const int _y1, const int _x2, const int _y2) {
	
	x1 = _x1;
	y1 = _y1;
	x2 = _x2;
	y2 = _y2;
	
	rSupG = NULL;
	rSupD = NULL;
	rInfG = NULL;
	rInfD = NULL;
	
	nbRegion++;
}

Region::~Region() {
	nbRegion--;
}
  	
bool Region::homogene(IplImage *img) {

	int r,b,v;
	CvScalar scal;
	
	for (int i = x1+1 ; i < x2-1; i++) {
		for (int j = y1+1 ; j < y2-1 ; j++) {
			
			scal = cvGet2D(img, j, i);
			
			if (i == x1+1 && j == y1+1) {
				
				//r = scal.val[2];
				b = scal.val[0];
				//v = scal.val[1];

			} else {
				//if (r != scal.val[2] || b != scal.val[0] || v != scal.val[1]) {
				if (b != scal.val[0]) {
					std::cout<< "Difference de couleur  b : "<<b<<" "<<scal.val[0]<<std::endl;
					return false;
				}
			}
			
		}
	}
	

	//std::cout<<"Test d'homogeneite"<<std::endl;
	return true;
}

void Region::subdivide(IplImage *img) {

	CvScalar scalairesg;
	scalairesg.val[1] = 255;
	CvScalar scalairesd;
	scalairesd.val[0] = 255;
	CvScalar scalaireig;
	scalaireig.val[2] = 255;
	CvScalar scalaireid;
	scalaireid.val[1] = 255;
	scalaireid.val[0] = 255;	

	
	
	if (!homogene(img)) {
	  
	  std::cout<<"_____!HOMOGENE__________"<< x1 << " " <<y1 << " " <<x2 << " " << y2<<std::endl;
	
	  int demi = (x2 -x1) / 2;
		
	  rSupG = new Region(x1,y1,x1 + demi ,y1 + demi);
	  rSupG->subdivide(img);
	  
	  rSupD = new Region(x1 + demi,y1,x2,y1 + demi);
	  rSupD->subdivide(img);
	  
	  rInfG = new Region(x1 ,y1 + demi, x1 + demi ,y2);
	  rInfG->subdivide(img);
	  
	  
	  rInfD = new Region(x1 + demi,y1 + demi, x2,y2);
	  rInfD->subdivide(img);
	    
	
	} else {
	
		//On colorie le tour de la region
		for (int i = x1 ; i < x2; i++) {
			for (int j = y1 ; j < y2 ; j++) {
			
				//On colorie le tour de la region
				if (i == x1 || i == x2-1 || j == y1 || j == (y2-1) ) {
					cvSet2D(img, j, i, scalairesg);
				}
			
			}
		
		}
	}
	
	//std::cout<<"Subdivide"<<std::endl;
}
  
